package com.bdqn.t350.dao.impl;

import com.bdqn.t350.dao.BaseDao;
import com.bdqn.t350.dao.ElectricityDao;
import com.bdqn.t350.entity.LineDataEntity;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ElectricityDaoImp extends BaseDao implements ElectricityDao {

    Connection conn;
    PreparedStatement pstmt;
    ResultSet rs;

    @Override
    public List<String> getElectricityTime() {
        String sql = "select month from electricity_time where id <=6";
        List<String> list = new ArrayList<>();
        try {
            conn = this.getConnection();
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();
            while (rs.next()) {
                list.add(String.valueOf(rs.getInt(1)));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            this.closeAll(conn, pstmt, rs);
        }
        return list;
    }

    @Override
    public List<String> findByElectricityName() {
        String sql = "select DISTINCT(name) from electricity_name n,(select * from electricity_time where id <=6) as e\n" +
                "where n.electricityTime_id = e.month";
        List<String> list = new ArrayList<>();
        try {
            conn = this.getConnection();
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();
            while (rs.next()) {
                list.add(rs.getString(1));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            this.closeAll(conn, pstmt, rs);
        }
        return list;
    }

    @Override
    public LineDataEntity findByElectricityNameCount(String name) {
        String sql = "select n.id,n.name,n.degree,n.electricityTime_id from electricity_name n,(select * from electricity_time where id <=6) as e \n" +
                "where n.electricityTime_id = e.month and n.name = ? order by month desc";
        LineDataEntity lineDataEntity = new LineDataEntity();
        lineDataEntity.setName(name);
        List<Integer> list = new ArrayList<>();
        try {
            conn = this.getConnection();
            pstmt = conn.prepareStatement(sql);
            pstmt.setObject(1, name);
            rs = pstmt.executeQuery();
            while (rs.next()) {
                list.add(rs.getInt("degree"));
            }
            Integer[] values = list.toArray(new Integer[list.size()]);
            lineDataEntity.setValue(values);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            this.closeAll(conn, pstmt, rs);
        }
        return lineDataEntity;
    }
}
